package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.domain.*;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.mapper.OrderDetailMapper;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.CartService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private AddressMapper addressMapper;
    @Autowired
    private CartService cartService;
    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Override
    public void  save (Order order){
        //获取用户
        User user = UserHolder.get();



        //获取user购物车信息
        List<Cart > cartList = cartService.findList();
        if (CollectionUtil.isNotEmpty(cartList)){
            throw new CustomException("购物车为空");
        } {
            //不为空的话。判断收货地址
        }
        Address address = addressMapper.selectById(order.getAddressId());
        if (address == null){
            throw new CustomException("地址为空");

        }
        //生成ID
        long orderId = IdWorker.getId();//雪花算法

        BigDecimal total = new BigDecimal(0);
        for (Cart cart : cartList){
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(cart.getName());
            orderDetail.setOrderId(orderId);
            orderDetail.setDishId(cart.getDishId());
            orderDetail.setSetmealId(cart.getSetmealId());
            orderDetail.setDishFlavor(cart.getDishFlavor());
            orderDetail.setNumber(cart.getNumber());
            orderDetail.setAmount(cart.getAmount());
            orderDetail.setImage(cart.getImage());


            //保存到订单详情数据表
            orderDetailMapper.insert(orderDetail);

            total = total.add(cart.getAmount().multiply(new BigDecimal(cart.getNumber())));//总金额。每次遍历的时候加上金额

        }
        //生成订单
        order.setId(orderId);
        order.setNumber(orderId+"");
        order.setStatus(0);//状态，待付款
        order.setUserId(user.getId());
        order.setOrderTime(new Date());
        order.setCheckoutTime(new Date());
        order.setAmount(total);//总金额
        order.setUserName(user.getName());
        order.setPhone(user.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());
        orderMapper.insert(order);
        cartService.clean();


    }
}
